package com.gooda.spring_boot_exp3.service.impl;

import com.gooda.spring_boot_exp3.entity.VirusStats;
import com.gooda.spring_boot_exp3.service.VirusService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
@Slf4j
public class VirusServiceImpl implements VirusService {

    RestTemplate restTemplate = new RestTemplate();
    final String URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(URL))
            .headers(headers -> headers.add("User-Agent", "Mozilla/5.0"))
            .build();

    ResponseEntity<Resource> responseEntity;

    Resource body;

    private List<VirusStats> virusData = new ArrayList<>();

    @Override
    @Scheduled(cron = "0 0 1 * * *")
    @PostConstruct
    public void updateVirusStats() throws IOException {

        responseEntity = restTemplate.exchange(requestEntity, Resource.class);
        body = responseEntity.getBody();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body.getInputStream()));

        Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader("Province/State", "Country/Region", "Lat", "Long")
                .parse(bufferedReader);
        Iterator<CSVRecord> iterator = records.iterator();
        iterator.next();
        while (iterator.hasNext()) {
            CSVRecord csvRecord = iterator.next();

//            log.info(csvRecord.toString());
            VirusStats virusStats = new VirusStats(
                    csvRecord.get("Province/State"),
                    csvRecord.get("Country/Region"),
                    Integer.parseInt(csvRecord.get(csvRecord.size()-1)),
                    Integer.parseInt(csvRecord.get(csvRecord.size()-1)) - Integer.parseInt(csvRecord.get(csvRecord.size()-2))
            );

            if (virusStats.getCountry().contains("Taiwan")) {
                virusStats.setCountry("China");
                virusStats.setState("Taiwan");
            }

            this.virusData.add(virusStats);
            log.info("virusData Updated");
        }
    }

    public List<VirusStats> getVirusData() {
        return this.virusData;
    }
}
